<?php
namespace Book\Controller;

use Think\Controller\RestController;
use Think\Exception;

class BookController extends RestController
{

    public static $book;

    public function _initialize()
    {
        $info = I('get.');
        if (!session('username') || !$info['namespace'] || session('username') !== $info['namespace']) {
            throw new Exception("Error Processing Request", 1);
        }
        $detail = D('Book')->getBook($info['namespace'], $info['name']);
        if (empty($detail)) {
            throw new \Think\Exception('不存在');
        }
        self::$book = $detail;
    }

    public function index()
    {
        $info = I('get.');
        if ($this->_method == 'delete') {
            //删除文档
            D('Book')->deleteBook($info['namespace'], $info['name']);
            $this->ajaxReturn(['redirect' => '/dashboard']);
        }
    }
    public function dashboard()
    {
        $namespace = I('get.namespace');
        $name      = I('get.name');
        $this->assign('name', $name);
        $this->assign('namespace', $namespace);
        $this->display();
    }

    public function test()
    {
        $content = M('book_chapter_release')->where(['id' => 55])->getField('content');
        var_dump(D('BookRelease')->getTree($content));
    }

    public function edit()
    {

        $info   = I('get.');
        $detail = self::$book;

        //生成一个token，存到数据库中，session中
        $token = D('Book')->createToken($detail['id']);

        $options['book']        = $detail;
        $options['token']       = $token;
        $options['environment'] = 'editor';
        $options['tool']        = [
            'dashboard' => "/book/{$detail['namespace']}/{$detail['name']}/dashboard",
            'preview'   => "/book/{$detail['namespace']}/{$detail['name']}/preview",
            'help'      => "https:\/\/help.kancloud.cn",
        ];
        $options['plugins'] = [
            'host'   => 'plugins.kancloud.cn',
            'scheme' => 'https',
        ];
        $options['web'] = [
            'host'   => 'www.kancloud.cn',
            'scheme' => 'https',
        ];
        $options['git'] = [
            'host'   => C('GIT_WEBSOCKET_URL'),
            'scheme' => C('GIT_WEBSOCKET_SCHEME'),
        ];
        // $options['git'] = [
        //     'host' => 'git.kancloud.cn',
        //     'scheme' => 'https',
        // ];

        $this->assign('json_options', json_encode($options));
        $this->display();
    }

    public function setting()
    {
        $detail = self::$book;
        if (IS_POST) {
            $info                  = I('post.');
            $update['title']       = $info['title'];
            $update['description'] = $info['description'];
            $update['tags']        = $info['tags'];

            $result = D('Book')->saveSetting($detail['id'], $update);
            
            if ($result) {
                header('Status: 204 No Content');
            }
        } else {

            $this->assign('Detail', $detail);
            $this->display();
        }
    }

    public function settingToggle()
    {
        if (IS_POST) {
            $info   = I('post.');
            $detail = self::$book;

            switch ($info['field']) {
                case 'auto_release':
                    $update['auto_release'] = $info['toggle'] == 'on' ? 1 : 0;
                    break;

                default:
                    //报错
                    header('Status: 422 Unprocessable Entity');
                    $this->ajaxReturn(['field' => 'field必须在 comment,download,reward,kindle,auto_release 范围内']);
                    break;
            }
            $result = D('Book')->saveSetting($detail['id'], $update);
            if ($result) {
                header('Status: 204 No Content');
            }
        }
    }

    public function release()
    {
        $detail = self::$book;
        if (IS_POST) {
            //加到发布计划列表中
            D('BookRelease')->addRelease($detail);
            $this->ajaxReturn(['redirect' => "/book/{$detail['namespace']}/{$detail['name']}/release"]);
        } else {
            //获取版本
            $page_list = D('BookRelease')->where(['bookid' => $detail['id']])->select();
            $this->assign('Detail', $detail);
            $this->assign('page_list', $page_list);
            $this->display();
        }

    }

    public function releaseStatus()
    {
        $detail = self::$book;

        if ($detail['ref'] != $detail['release']) {

            $files = D('Book')->gitCompareTwoCommits($detail['repos_name'], $detail['release'], $detail['ref']);
            foreach ($files as $key => $value) {
                $files[$key]['patch'] = $this->parseDiff($value['patch']);
            }
            var_dump($files);exit;
            $this->assign('files', $files);
            $this->display();
        } else {
            //返回
            header('Status: 422 Unprocessable Entity');

            if ($detail['release_status'] == 1) {
                echo '文档正在发布中，请稍后再试';
            } else {
                echo '当前已是最新版本';
            }

        }
    }

    public function publish()
    {
        $detail = self::$book;
        D('BookRelease')->publish($detail['id']);
    }

    private function parseDiff($patch)
    {
        return $patch;
        //按@@ -5,8 +5,6 @@区分
        preg_match_all('/@@.*@@[^@@]+/i', $patch, $matches);
        foreach ($matches[0] as $key => $value) {
            $skips = [];
            $arr   = explode("\n", $value);

            foreach ($arr as $key => $value) {
                if ($key == 0) {
                    $skips['skip'] = $arr[0];
                    continue;
                }
                //
            }
            var_dump($arr);exit;
        }
        var_dump($matches);exit;
    }

    public function releaseCheck()
    {
        $info   = I('get.');
        $detail = self::$book;
        if ($detail['status'] == 0) {
            header('Status: 449 Retry With');
        } else {
            $this->ajaxReturn(['redirect' => "/book/{$info['namespace']}/{$info['name']}/release"]);
        }

    }
    public function getSummary(){
        $detail = self::$book;
        //获取目录，保存到summmary
        $content = $this->getSummaryFromSource($detail['source'], $detail['source_id']);
        
        //保存到内容
        $info['content'] = base64_encode($content);
        $info['type'] = 'update';
        $info['sha'] = '';
        $info['blob_sha'] = '';
        $result = D('BookChapter')->updateChapter($detail['id'], 'SUMMARY.md', $info);
        // array_multisort(array_keys($query_content), SORT_DESC, $query_content);
        // rsort($query_content);

        var_dump($result);

    }

    public function getSummaryFromSource($source, $source_id, $page = 1){
        switch ($source) {
            case 'm.wuyouhui.net':
                //漫画
                $url = 'http://'.$source.$source_id;
                $snoopy = new \Lain\Snoopy;
                $snoopy->rawheaders["Pragma"] = "no-cache";
                //代理
                // $snoopy->proxy_host = S('proxy_host');
                // $snoopy->proxy_port = S('proxy_port');
                
                $snoopy->fetch($url);
                $html_code = $snoopy->results;
                //使用QueryList解析html
                $rules = [
                    'title' => ['.Drama li a span', 'html'],
                    'href' => ['.Drama li a', 'href'],
                ];
                $query_content = \QL\QueryList::Query($html_code, $rules)->data;
                // var_dump($query_content);exit;
                //原本为降序，改为升序
                $count = count($query_content);
                $content = '';
                for($i = $count-1; $i >= 0; $i--){
                    $content .= sprintf("* [%s](%s.md)\n", $query_content[$i]['title'], 'm.wuyouhui.net'.$query_content[$i]['href']);
                }
                break;
            case 'k.xinshubao.net':
                //小说
                $url = 'https://'.$source.'/chapters_'.$source_id.'_'.$page.'/';
                $snoopy = new \Lain\Snoopy;
                $snoopy->rawheaders["Pragma"] = "no-cache";
                //代理
                // $snoopy->proxy_host = S('proxy_host');
                // $snoopy->proxy_port = S('proxy_port');
                
                $snoopy->fetch($url);
                $html_code = $snoopy->results;
                //转utf8
                $html_code = iconv('GB2312', 'UTF-8', $html_code);
                $html_code = substr($html_code, 50);
                //使用QueryList解析html
                $rules = [
                    'title' => ['.list li a', 'html'],
                    'href' => ['.list li a', 'href'],
                ];
                $page_rules = [
                    'title' => ['.page:eq(1)', 'text'],
                ];
                // $range = '.block';
                $query_content = \QL\QueryList::Query($html_code, $rules)->data;
                if($page==1){
                    //获取总页
                    $query_page = \QL\QueryList::Query($html_code, $page_rules)->data;
                    preg_match('/\(\d+\/(\d+)\)/i', $query_page[0]['title'], $matches);
                    $total = $matches[1];
                    for($i = 2; $i <= $total; $i++){
                        $next_content = $this->getSummaryFromSource($source, $source_id, $i);
                        $query_content = array_merge($query_content, $next_content);
                    }
                }else{
                    return $query_content;
                }
                $count = count($query_content);
                $content = '';
                for($i = 0; $i < $count; $i++){
                    $content .= sprintf("* [%s](%s.md)\n", $query_content[$i]['title'], str_replace(['https://'], '', $query_content[$i]['href']));
                }
                break;
            
            default:
                # code...
                break;
        }
        return $content;
    }
}
